{-# LANGUAGE OverloadedStrings,InstanceSigs,TupleSections    #-}
{-# LANGUAGE QuasiQuotes,MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell,TypeFamilies,FlexibleInstances #-}
module CMS.View.Admin.Article (wCateList,wAddArticle,wArticleList,wEditorArticle) where
import CMS.View.Admin.Common
import CMS.Data
import Yesod
import App.Article.DB
import Data.Int
import App.Article.Manager
import Data.Aeson
import Text.Julius
import Data.Text
import App.Common.Table

wCateList::[(Int64,ArticleCate)] -> CateNode Text -> Widget
wCateList cateList cNode = do
  addScriptRemote "/static/Admin/vendor/treeview/bootstrap-treeview.min.js"
  addStylesheetRemote "/static/Admin/vendor/treeview/bootstrap-treeview.min.css"
  [whamlet|
   <div .row>
    <div .col-lg-12>
     <h1 .page-header>文章分类
     <form #delForm method="POST" action="@{AdminR AdminArticleCateDelR}">
      <input #delId type="hidden" name="delId" value="0">
     <form .form-inline method="POST" action="@{AdminR AdminArticleCateAddR}">
       <label .sr-only for="cateName">Name
       <input name="cateName" #cateName .form-control .mb-2 .mr-sm-2 type="text" placeholder="分类名称">
       <label .sr-only for="pid">Name
       <select .form-control name="pid">
         <option value="-1">顶级分类
         $forall (id,cate) <- cateList
           <option value="#{id}">#{articleCateName cate}
       <label .sr-only for="subBtn">
       <button .btn .btn-primary .mb-2 .form-control>添加
     <hr>
     <div #tree>
   |]
  wCss
  wJS cNode
   where
     wJS::CateNode Text -> Widget
     wJS ccNode = toWidget $ [julius|
       function getTree()
       {
         var data = JSON.parse('#{toJSON $ nodes ccNode}');
         for(var i = 0;i<data.length;i++)
         {
           loopNode(data[i],appendButton);
         }
         return data;
       }
       function appendButton(node)
       {
          if(node.nodes.length ==0)
          {
            node.text += "<button onclick='javascript:deleteCate("+node.cateId+")' class='btn btn-info tree_btn'>删除</button>";
          }
       }
       function loopNode(node,fn)
       {
           fn(node);
           for(var i = 0; i < node.nodes.length;i++)
           {
              loopNode(node.nodes[i],fn);
           }
       }
       function deleteCate(id)
       {
          $("#delId").val(id);
          $("#delForm").submit();
       }
       $('#tree').treeview({data: getTree(),selectedBackColor: "#FFFFFF",selectedColor:"#000"});
       $('#tree').treeview('expandAll',{levels: 5, silent: true} );
     |]
     wCss = toWidget [lucius|
      .tree_btn {float:right; z-index:999;margin-top: 5px;}
      .node-tree {line-height:40px;}
     |]

wArticleLink:: Widget
wArticleLink  = do
  addScriptRemote "/static/Admin/vendor/markdown-it/markdown-it.js"
  addScriptRemote "/static/Admin/vendor/highlight/highlight.pack.js"
  addStylesheetRemote "/static/Admin/vendor/highlight/styles/vs.css"

wArticleJs::Widget
wArticleJs = toWidget [julius|
  var md = window.markdownit({html:true});
  function updateMD()
  {
    let renderHTML = md.render($("#srcMD").val());
    $("#renderMD").html(renderHTML);
    $("pre code").each(function(i, block) {hljs.highlightBlock(block);});
  }
  updateMD();
  $("#srcMD").on("keyup",function()
  { 
     updateMD();
  });
  function onSubmit()
  {
     if($("#articleTitle").val() == "")
     {
        alert("标题不可为空");
        return;
     }
     if($("#srcMD").val() == "")
     {
       alert("正文不可为空");
       return;
     }
     $("#articleForm").submit();
  }
|]

wEditorArticle::(Int64,Article) -> [(Int64,ArticleCate)]  -> Widget
wEditorArticle (eid,article) cateList = do
  wArticleLink
  [whamlet|
   <div .row>
    <div .col-lg-12>
     <h1 .page-header>编辑文章
     <form #articleForm action="@{AdminR $ AdminArticleEditorR eid}" method="POST">
       <input  name="title" #articleTitle .form-control placeholder="文章标题" value="#{articleTitle article}" style="float:left;width:50%">
       <select name="pid" .form-control style="float:left;width:20%;margin-left:1%">
         $forall (id,cate) <- cateList
            $with isSel <- (articleOwnerCateId article) == id
             <option value="#{id}" :isSel:selected="selected">#{articleCateName cate}
       <button type="button" .btn .btn-primary onclick="onSubmit()" style="float:left;margin-left:10px;width:150px;">提交
       <div style="clear:both;height:20px">
       <label>仅自己可见
       <input  type="checkbox" name="isPrivate" :(articleIsPrivate article):checked value="true">
       <div style="clear:both;height:20px">
       <textarea name="context" #srcMD style="width:46%;height:500px;float:left">#{articleContext article}
       <div #renderMD style="float:right;width:54%;min-height:500px;border:1px solid #eee;padding:10px;">
  |]
  wArticleJs


wAddArticle::[(Int64,ArticleCate)] -> Widget
wAddArticle cateList = do
 wArticleLink
 [whamlet|
 <div .row>
  <div .col-lg-12>
   <h1 .page-header>添加文章
   <form #articleForm action="@{AdminR AdminArticleAddR}" method="POST">
    <input  name="title" #articleTitle .form-control placeholder="文章标题" style="float:left;width:50%">
    <select name="pid" .form-control style="float:left;width:20%;margin-left:1%">
       $forall (id,cate) <- cateList
         <option value="#{id}">#{articleCateName cate}
    <button type="button" .btn .btn-primary onclick="onSubmit()" style="float:left;margin-left:10px;width:150px;">提交
    <div style="clear:both;height:20px">
    <label>仅自己可见
    <input  type="checkbox" name="isPrivate" value="true">
    <div style="clear:both;height:20px">
    <textarea name="context" #srcMD style="width:46%;height:500px;float:left">
    <div #renderMD style="float:right;width:54%;min-height:500px;border:1px solid #eee;padding:10px;">
 |]
 wArticleJs


wArticleList::Table (Int64,Article) -> Widget
wArticleList tabArticle = do
   [whamlet|
   <div .row>
    <div .col-lg-12>
     <h1 .page-header>文章列表
     <form #delForm method="POST" action="@{AdminR AdminArticleDelR}">
      <input #delId name="delId" type="hidden">
     <table .table .table-striped .table-bordered .table-hover .dataTable>
        <thead>
         <tr>
          <th width="50px">ID
          <th >标题
          <th width="150px">操作
        <tbody>
          $forall (id,article) <- tableData tabArticle
           <tr>
            <td>#{show id}
            <td>#{articleTitle article}
            <td>
             &nbsp;&nbsp;&nbsp;&nbsp;
             <a href="javascript:delArticle(#{id})">删除
             &nbsp;&nbsp;&nbsp;&nbsp;
             <a href="@{AdminR $ AdminArticleEditorR id}">编辑
          <tr>
           <td colspan="3" align="center" .tabpager>
              $if isPrv tabArticle
                $with decCP <- (fromIntegral $ curPage $ pageInfo tabArticle) - 1
                 <a .btn .btn-primary href="@{AdminR $ AdminArticleListR decCP}">上一页
              $else
                <a .btn .btn-secondary href="#">上一页
              $with curP <- (curPage $ pageInfo tabArticle) + 1
               <span>#{curP}/#{maxPage tabArticle}
              $if isNext tabArticle
                $with incCP <- (fromIntegral $ curPage $ pageInfo tabArticle) + 1
                 <a .btn .btn-primary href="@{AdminR $ AdminArticleListR incCP}">下一页
              $else
                 <a .btn .btn-secondary href="#">下一页

   |]
   wJs
 where
  wJs::Widget
  wJs = toWidget $ [julius|
     function delArticle(delId)
     {
       $("#delId").val(delId);
       $("#delForm").submit();
     }
  |]